import React, { Component } from 'react';
import { Select } from 'antd';
import fetch from 'dva/fetch';
// import querystring from 'querystring';

const { Option } = Select;

class SearchInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      value: undefined,
      url: props.url,
      form: props.form,
      sName: props.sName,
      token: props.token,
    };
    this.timeout = 0;
    this.currentValue = '';
  }

  componentWillReceiveProps(nextProps) {
    const {
      url, form, sName, token,
    } = nextProps; /* 显示配置 */
    this.setState({
      url, form, sName, token,
    });
  }

  handleSearch = (value) => {
    this.fetchData(value, data => this.setState({ data }));
  }

  handleChange = (value, option) => {
    this.props.handleChange(value, option);
  }

  fake = (url, form, sName, token, currentValue, value, callback) => {
    const values = {
      sKeyUpFilterName: '', /* {        sCustomerName: form.getFieldValue(sName),
      } */
      sSqlCondition: '',
    };
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
      body: JSON.stringify(values),
    };
    fetch(url, options)
      .then(response => response.json())
      .then((json) => {
        if (currentValue === value) {
          const result = json.dataset.rows;
          const data = [];
          result.forEach((r) => {
            data.push({
              value: r.sId,
              text: r.sCustomerName,
            });
          });
          callback(data);
        }
      });
  }

  fetchData = (value, callback) => {
    const { timeout } = this;
    if (timeout) {
      clearTimeout(timeout);
      this.timeout = null;
    }
    this.currentValue = value;
    const {
      url, form, sName, token,
    } = this.state;
    this.timeout = setTimeout(this.fake(url, form, sName, token, this.currentValue, value, callback), 300);
  }

  render() {
    const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);
    return (
      <Select
        showSearch
        value={this.state.value}
        placeholder={this.props.placeholder}
        style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={this.handleSearch}
        onSelect={this.handleChange}
        notFoundContent={null}
      >
        {options}
      </Select>
    );
  }
}
export default SearchInput;
